(function(){
    var session = twc.session;
    var dlg, alertTimer, logoutTimer;
    var modal = "#session-timeout-modal";

    function refreshLogin(){

        //Sending all browsers down the sessionRefreshURL since the iframe/reload isn't working for non-IE browsers
        window.location = twc.session.sessionRefreshUrl;

        ////Workaround for IE. Can't redirect iframes without p3p header
        //if($.browser.msie && $.browser.msie){
        //    window.location = twc.session.sessionRefreshUrl;
        //} else {
        //    var frame_loaded = false;
        //    var iframe = $("<iframe>", { src: twc.session.sessionRefreshUrl }).css({
        //        height: 0,
        //        width: 0,
        //        style: "-9999px"
        //    });

        //    iframe.on("load", function(){
        //        if (frame_loaded)
        //            return;

        //        frame_loaded = true;

        //        clearTimers();
        //        setTimeout(function(){
        //            scheduleNotifier();
        //            iframe.remove();
        //        }, 15000);
        //    }).appendTo('body');

        //    window.location.reload() // reloading the window so CSRF tokens get re-written to the hidden form input elements that contain them
        //}
    }

    function showModal(){
        dlg = dlg || $(modal).modal({ backdrop: "static" });
        dlg.modal("show");
    }

    function hideModal(){
        dlg.modal("hide");
    }

    function clearTimers(){
        clearTimeout(alertTimer);
        clearTimeout(logoutTimer);
    }

    function logout(){
        clearTimers();
        window.location = session.logoutUrl;
    }

    function scheduleNotifier(){
        var url = session.sessionExpirationUrl;
        var opts = { dataType: "jsonp", method: "GET" };

        $.ajax(url, opts).done(function(resp){
            var result = resp.result;

            if (!result || result.error) {
                logout();
            } else {
                var delay = +result.timeout;

                alertTimer = setTimeout(showModal, delay - session.numMillisBeforeLogoutToNotifyUser);
                logoutTimer = setTimeout(logout, delay);
            }

        }).fail(logout);
    }

    // event handlers
    $(window).on("unload", clearTimers);
    $(document).on("click", modal+" a", function(){
        hideModal();

        if ($(this).data("action") == "login"){
            refreshLogin();
        } else {
            logout();
        }
    });

    $('.sign-out-link').on('click', function() {
        $(window).trigger('logout');
    });

    // initialize timer
    scheduleNotifier();
}());

jpackage('twc.ajaxLoader', function(){
    var doc = $(document);

    this.fetchData = function(e) {
        var el = $(this);

        var url = el.data('ajax-url');
        var replace = el.data('ajax-replace');

        $.ajax(url, {cache: false}).done(function(resp){
            var evt = url.split('/').pop().split('?').shift().replace(/^ajax_/, '');
            var html = $(resp);//.hide();

            doc.trigger('pre_ajax.'+ evt);

            if (replace) el.empty().append(html);
            else el.after(html);

            //html.slideDown(500);

            doc.trigger('ajax.' + evt);
            doc.trigger('ajax.complete');

        }).fail(function(req){
            var txt = req.responseText, err;

            if (txt.match(/!DOCTYPE html/)){
                txt = twc.utils.template('data-error')({ message: 'We\'re sorry but your request has failed.' });
                txt = '<div class="row main fail">'+ txt +'</div>';
            }

            replace ? el.html(txt) : el.after(txt);

        }).always(function(){
            el.removeClass('async');
        });
    };
});

$(function() {
    // kickoff ajax loader
    $('div[data-ajax-url]').each(twc.ajaxLoader.fetchData);
});

jpackage("twc.quicklinks", function(){
	var url = twc.routes.get('data/quicklinks');
	$.ajax(url).done(function(resp) {
        $('a.quick-links ul').html(resp);
		if ($('a.quick-links ul li').length > 0) {
			$('a.quick-links').css('display','block');
		}
        $('.buttons > a').css('float','left');
        $('.buttons form').css('float','left');
	});
});

(function(){
	
    function setFSRDivisionProperty() {
    	//initialize the foresee survey FSR.properties systemdivision variable
    	$.ajax(twc.routes.get('public/division')).done(function(resp){
    		if (resp && !resp.error) {
    	    	FSR.CPPS.set('divisionsystem', resp.division.soaDivisionId);
    	    }
    	})
    }
    
    setFSRDivisionProperty();
}());


